package com.phoenix.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.phoenix.entity.GroupMember;
import com.phoenix.entity.ResponseData;
import com.phoenix.entity.UserMember;
import com.phoenix.entity.Users;
import com.phoenix.service.GroupMemberService;
import com.phoenix.service.UserMemberService;
import com.phoenix.service.UserService;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequiresRoles(value = {"admin", "user"}, logical = Logical.OR)
@RequestMapping("/info")
public class InfoController {
    @Autowired
    UserMemberService userMemberService;
    @Autowired
    GroupMemberService groupMemberService;
    @Autowired
    UserService userService;

    @PostMapping("/userMemberAdd")
    public String userMemberAdd(HttpServletResponse response, Model model, UserMember userMember) throws UnsupportedEncodingException {
        Subject currentUser = SecurityUtils.getSubject();
        String userName = (String) currentUser.getPrincipal();
        Users user = userService.selectUserByUsername(userName);
        if (user.getRole().equals("admin")) {
            Boolean update = userMemberService.updateUserMember(userMember);
            if (update) {
                model.addAttribute("msg", "审批成功");
                PDFController pdfController = new PDFController();
                pdfController.exportMember(response, userMember);
            } else {
                model.addAttribute("msg", "审批失败");
            }
            return "admin/approvalMemberInfo";
        } else {
            userMember.setStatus("待审核");
            if (userMember.getInfoID() != null) {
                Boolean update = userMemberService.updateUserMember(userMember);
                if (update) {
                    model.addAttribute("msg", "修改成功");
                } else {
                    model.addAttribute("msg", "修改失败");
                }
            } else {
                userMember.setUserID(user.getUserID());
                Boolean add = userMemberService.addUserMember(userMember);
                if (add) {
                    model.addAttribute("msg", "提交成功，如需修改请前往编辑页面");
                } else {
                    model.addAttribute("msg", "提交失败");
                }
            }
            return "user/memberInfo";
        }
    }

    @PostMapping("/groupMemberAdd")
    public String groupMemberAdd(HttpServletResponse response, Model model, GroupMember groupMember) throws UnsupportedEncodingException {
        Subject currentUser = SecurityUtils.getSubject();
        String userName = (String) currentUser.getPrincipal();
        Users user = userService.selectUserByUsername(userName);
        if (user.getRole().equals("admin")) {
            Boolean update = groupMemberService.updateGroupMember(groupMember);
            if (update) {
                model.addAttribute("msg", "审批成功");
                PDFController pdfController = new PDFController();
                pdfController.exportGroup(response, groupMember);
            } else {
                model.addAttribute("msg", "审批失败");
            }
            return "admin/approvalGroupInfo";
        } else {
            groupMember.setStatus("待审核");
            if (groupMember.getGroupID() != null) {
                Boolean update = groupMemberService.updateGroupMember(groupMember);
                if (update) {
                    model.addAttribute("msg", "修改成功");
                } else {
                    model.addAttribute("msg", "修改失败");
                }
            } else {
                groupMember.setUserID(user.getUserID());
                Boolean add = groupMemberService.addGroupMember(groupMember);
                if (add) {
                    model.addAttribute("msg", "提交成功，如需修改请前往编辑页面");
                } else {
                    model.addAttribute("msg", "提交失败");
                }
            }
            return "user/groupInfo";
        }
    }

    @RequestMapping("/userMemberEdit")
    public String userMemberList(Model model, @RequestParam(value = "keywords", defaultValue = "") String keywords, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        //进行分页，提供关键字查询
        //pageSize为分页的行数
        Map<String, Object> search = new HashMap<>();
        search.put("keywords", keywords);
        Subject currentUser = SecurityUtils.getSubject();
        String userName = (String) currentUser.getPrincipal();
        Users user = userService.selectUserByUsername(userName);
        PageHelper.startPage(pageNum, pageSize);
        List<UserMember> list;
        if (user.getRole().equals("admin")) {
            list = userMemberService.adminSelectNSearch(search);
        } else {
            search.put("userID", user.getUserID());
            list = userMemberService.selectNSearch(search);
        }
        //使用PageHelper包装数据
        PageInfo<UserMember> pageInfo = new PageInfo<>(list);
        model.addAttribute("result", new ResponseData<>(200, "ok", pageInfo));
        model.addAttribute("keywords", keywords);
        return "user/memberInfoEdit";
    }

    @RequestMapping("/groupMemberEdit")
    public String groupMemberList(Model model, @RequestParam(value = "keywords", defaultValue = "") String keywords, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        //进行分页，提供关键字查询
        //pageSize为分页的行数
        Map<String, Object> search = new HashMap<>();
        search.put("keywords", keywords);
        Subject currentUser = SecurityUtils.getSubject();
        String userName = (String) currentUser.getPrincipal();
        Users user = userService.selectUserByUsername(userName);
        PageHelper.startPage(pageNum, pageSize);
        List<GroupMember> list;
        if (user.getRole().equals("admin")) {
            list = groupMemberService.adminSelectNSearch(search);
        } else {
            search.put("userID", user.getUserID());
            list = groupMemberService.selectNSearch(search);
        }
        //使用PageHelper包装数据
        PageInfo<GroupMember> pageInfo = new PageInfo<>(list);
        model.addAttribute("result", new ResponseData<>(200, "ok", pageInfo));
        model.addAttribute("keywords", keywords);
        return "user/groupInfoEdit";
    }

    //批量删除
    @DeleteMapping("/memberDel")
    @ResponseBody
    public ResponseData<String> memberDel(@RequestParam String infoID) {
        //Some Magic.
        String[] IDS = infoID.split(",");
        List<String> IDList = Arrays.asList(IDS);
        Boolean test = userMemberService.deleteUserMemberByList(IDList);
        if (test) {
            return new ResponseData<>(200, "删除成功！", null);
        } else {
            return new ResponseData<>(500, "删除失败！", null);
        }
    }

    @DeleteMapping("/groupDel")
    @ResponseBody
    public ResponseData<String> adminDel(@RequestParam String groupID) {
        //Some Magic.
        String[] IDS = groupID.split(",");
        List<String> IDList = Arrays.asList(IDS);
        Boolean test = groupMemberService.deleteGroupMemberByList(IDList);
        if (test) {
            return new ResponseData<>(200, "删除成功！", null);
        } else {
            return new ResponseData<>(500, "删除失败！", null);
        }
    }

    //单条删除
    @DeleteMapping("/delMember/{infoID}")
    @ResponseBody
    public ResponseData<String> del(@PathVariable String infoID) {
        Boolean test = userMemberService.deleteUserMember(Integer.valueOf(infoID));
        if (test) {
            return new ResponseData<>(200, "删除成功！", null);
        } else {
            return new ResponseData<>(500, "删除失败！", null);
        }
    }

    @DeleteMapping("/delGroup/{groupID}")
    @ResponseBody
    public ResponseData<String> delGroup(@PathVariable String groupID) {
        Boolean test = groupMemberService.deleteGroupMember(Integer.valueOf(groupID));
        if (test) {
            return new ResponseData<>(200, "删除成功！", null);
        } else {
            return new ResponseData<>(500, "删除失败！", null);
        }
    }
}
